﻿//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Windows.Forms;

namespace OfficeSWORD.Common
{
    public partial class DepositForm : Form
    {
        static string AppNamespace = "http://www.w3.org/2007/app";
        static string AtomNamespace = "http://www.w3.org/2005/Atom";

        class CollectionInfo
        {
            public string Title;
            public string Uri;
            public override string ToString()
            {
                return this.Title;
            }
        }

        string endpoint;
        string filename;

        public DepositForm(string endpoint, string fileToDeposity)
        {
            this.endpoint = endpoint;
            this.filename = fileToDeposity;

            InitializeComponent();

            // We should do this in a background thread
            try
            {
                this.labelEndpoint.Text = this.endpoint;

                // Try to get the service document from the endpoint
                HttpWebRequest request = HttpWebRequest.Create(this.endpoint + "/ServiceDocument") as HttpWebRequest;
                request.Method = "GET";

                var response = request.GetResponse() as HttpWebResponse;
                var doc = XDocument.Load(new StreamReader(response.GetResponseStream()));
                
                // Deal with one workspace only
                var service = doc.Element(XName.Get("service", DepositForm.AppNamespace));
                if (service != null)
                {
                    var workspace = service.Element(XName.Get("workspace", DepositForm.AppNamespace));
                    if (workspace != null)
                    {
                        var title = workspace.Element(XName.Get("title", DepositForm.AtomNamespace));
                        if (title != null)
                        {
                            this.labelWorkspace.Text = title.Value;
                        }

                        foreach (XElement collection in doc.Descendants(XName.Get("collection", DepositForm.AppNamespace)))
                        {
                            // TODO Must check that the 'title' element and 'href' attribute exist
                            var t = collection.Element(XName.Get("title", DepositForm.AtomNamespace)).Value;
                            var u = collection.Attribute(XName.Get("href")).Value;
                            this.listBoxCollection.Items.Add(new CollectionInfo { Title = t, Uri = u });
                        }
                    }
                }
            }
            catch (Exception)
            {
                // Problem retrieving from the endpoint... disable the deposit button
                this.buttonDeposit.Enabled = false;
            }
        }

        private void buttonDeposit_Click(object sender, EventArgs e)
        {
            // Create a temporary copy of the document and send it
            string filenameForTmp = this.filename + "SWORDDeposit-DeleteMe";

            try
            {
                // Create the request
                string uri = ((CollectionInfo)this.listBoxCollection.SelectedItem).Uri;
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.Method = "POST";
                request.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

                // Copy the file
                File.Copy(this.filename, filenameForTmp, true);

                // Add contents to the request stream
                using (FileStream fs = File.Open(filenameForTmp, FileMode.Open, FileAccess.Read))
                {
                    // Assume a small file
                    byte[] contents = new byte[fs.Length];
                    fs.Read(contents, 0, (int)fs.Length);

                    using (Stream s = request.GetRequestStream())
                    {
                        s.Write(contents, 0, (int)fs.Length);
                    }

                    // Send the request to the service
                    request.GetResponse();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error during deposit");
            }
            finally
            {
                try
                {
                    if (File.Exists(filenameForTmp))
                    {
                        File.Delete(filenameForTmp);
                    }
                }
                catch (Exception)
                {
                    // ignore
                }
            }

            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void listBoxCollection_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.buttonDeposit.Enabled = this.listBoxCollection.SelectedItem != null;
        }
    }
}
